import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  // 改变state的token值
  setToken(state, token) {
    state.token = token
    setToken(token) // 同步给本地的缓存
  },
  // 移除state的token值
  removeToken(state) {
    state.token = '' // 清空state的token值
    removeToken() // 清空本地缓存的token值
  },
  setUserInfo(state, info) {
    state.userInfo = info
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }

}
const actions = {
  async login(context, data) {
    const result = await login(data)
    context.commit('setToken', result)
    setTimeStamp()
  },
  async getUserInfo(context) {
    const result = await getUserInfo()
    const baseInfo = await getUserDetailById(result.userId)
    const baseResult = { ...result, ...baseInfo }
    context.commit('setUserInfo', baseResult)
    return result // 这里为什么要返回 为后面埋下伏笔
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
